﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace umbraco
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI.WebControls;
    using umbraco.cms.businesslogic.member;
    using umbraco.ACSExtensions;

    public partial class ViewBusinessIdentityProviderMappings : BasePages.UmbracoEnsuredPage
    {
        private MappingRuleService mappingRuleService = new MappingRuleService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                var identityProviderName = this.Request.QueryString["identityProviderName"];
                this.MainPanel.Text = "Business Identity Providers -> " + identityProviderName;

                this.BindMappings();
            }
        }

        public void BindMappings()
        {
            var mappings = new List<MappingRule>();
            var identityProviderId = this.Request.QueryString["identityProviderId"];
            var identityProviderName = this.Request.QueryString["identityProviderName"];

            foreach (var memberGroup in MemberGroup.GetAll)
            {
                var groupMappings = mappingRuleService.RetrieveMappingsByMemberGroup(
                    new IdentityProviderInfo { Id = identityProviderId, Name = identityProviderName },
                    new MemberGroupInfo { Id =  memberGroup.Id, Name =  memberGroup.Text }).ToList();

                if (groupMappings.Count() == 0)
                {
                    groupMappings.Add(
                        new MappingRule 
                        {
                            IdentityProvider = new IdentityProviderInfo { Id = identityProviderId, Name = identityProviderName }, 
                            MemberGroup = new MemberGroupInfo { Id =  memberGroup.Id, Name =  memberGroup.Text } 
                        });
                }

                mappings.AddRange(groupMappings);
            }

            var result = (from m in mappings
                          group m by new { m.MemberGroup.Id, m.MemberGroup.Name } into g
                          select new MemberGroupMappingView 
                          { 
                              MemberGroupAlias = g.Key.Name,
                              MemberGroupId = g.Key.Id,
                              Mappings = g.ToList()
                          });

            this.MemberGroupsMappingsRepeater.DataSource = result;
            this.MemberGroupsMappingsRepeater.DataBind();
        }

        public void BindMemberGroupMappings(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Literal memberGroupTitle = (Literal)e.Item.FindControl("MemberGroupTitle");
                var identityProviderId = this.Request.QueryString["identityProviderId"];
                var identityProviderName = this.Request.QueryString["identityProviderName"];
                var item = (MemberGroupMappingView)e.Item.DataItem;

                memberGroupTitle.Text = "Mappings for the <a href='ViewMemberGroupMappings.aspx?identityProviderId=" + identityProviderId + "&identityProviderName=" + identityProviderName + "&memberGroupId=" + item.MemberGroupId + "&memberGroupName=" + item.MemberGroupAlias + "'>" + item.MemberGroupAlias + "</a> group";

                Repeater mappingsRepeater = (Repeater)e.Item.FindControl("MappingsRepeater");
                mappingsRepeater.DataSource = item.Mappings;
                mappingsRepeater.DataBind();
            }
        }

        public void BindMapping(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Literal claimType = (Literal)e.Item.FindControl("ClaimType");
                Literal claimValue = (Literal)e.Item.FindControl("ClaimValue");
                Button editButton = (Button)e.Item.FindControl("EditButton");
                Button deleteButton = (Button)e.Item.FindControl("DeleteButton");

                var mapping = (MappingRule)e.Item.DataItem;

                claimType.Text = mapping.ClaimType;
                claimValue.Text = mapping.ClaimValue;

                if (!string.IsNullOrEmpty(claimType.Text))
                {
                    editButton.CommandArgument = mapping.Id.ToString();
                    editButton.PostBackUrl = "EditMemberGroupMapping.aspx?mappingId=" + mapping.Id;
                    editButton.Text = ui.Text("edit");

                    deleteButton.CommandArgument = mapping.Id.ToString();
                    deleteButton.OnClientClick = "return confirm(\"" + ui.Text("confirmdelete") + " '" + mapping.Name + "' mapping rule ?\")";
                    deleteButton.Text = ui.Text("delete");
                }
                else
                {
                    editButton.Visible = false;
                    deleteButton.Visible = false;
                }
            }
        }

        public void DeleteMapping(object sender, CommandEventArgs e)
        {
            Guid mappingId = Guid.Empty;

            if (Guid.TryParse(e.CommandArgument.ToString(), out mappingId))
            {
                this.mappingRuleService.DeleteMapping(mappingId);
                this.BindMappings();
            }
        }
    }

    public class MemberGroupMappingView
    {
        public int MemberGroupId { get; set; }

        public string MemberGroupAlias { get; set; }

        public IEnumerable<MappingRule> Mappings { get; set; }
    }
}